#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time: 2024/10/29 11:13 上午
# @Author: wangyong
# @Version: 1.0.0
# @File: akshare_demo.py
# @Desc: akshare 测试
# @Link: https://zhuanlan.zhihu.com/p/678521592


import akshare as ak
import pandas as pd
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt




if __name__ == '__main__':

    # # 获取股票、基金和期货数据
    # stock_data = ak.stock_zh_a_daily(symbol="sz000001", start_date="2022-01-01", end_date="2022-12-31")
    # fund_data = ak.fund_scale_open_sina(symbol="股票型基金")
    # futures_data = ak.futures_zh_minute_sina(symbol="SA2501", period="1")
    # # 计算不同资产的年度收益率
    # stock_return = (stock_data["close"].iloc[-1] - stock_data["close"].iloc[0]) / stock_data["close"].iloc[0]
    # # fund_return = (fund_data["unit_nav"].iloc[-1] - fund_data["unit_nav"].iloc[0]) / fund_data["unit_nav"].iloc[0]
    # futures_return = (futures_data["close"].iloc[-1] - futures_data["close"].iloc[0]) / futures_data["close"].iloc[0]
    # # 打印投资组合报告
    # print("股票收益率：", stock_return)
    # # print("基金收益率：", fund_return)
    # print("期货收益率：", futures_return)
    #
    #
    # #  获取股票日线行情数据
    # stock_data = ak.stock_zh_a_daily(symbol="sz000001", start_date="2024-01-01", end_date="2024-12-31")
    # # 计算股票收益率
    # stock_data["return"] = stock_data["close"].pct_change()
    # print(stock_data["return"].describe())
    #
    # # 计算5日和20日均线
    # stock_data["ma5"] = stock_data["close"].rolling(window=5).mean()
    # stock_data["ma20"] = stock_data["close"].rolling(window=20).mean()
    #
    # # 生成买入信号（ma5向上穿越ma20）
    # stock_data["buy_signal"] = (stock_data["ma5"] > stock_data["ma20"]) & (stock_data["ma5"].shift(1) <= stock_data["ma20"].shift(1))
    #
    # # 生成卖出信号（ma5向下穿越ma20）
    # stock_data["sell_signal"] = (stock_data["ma5"] < stock_data["ma20"]) & (stock_data["ma5"].shift(1) >= stock_data["ma20"].shift(1))
    #
    # # 打印交易信号
    # signals = stock_data[["date", "buy_signal", "sell_signal"]]
    # print(signals)

    # 获取股票日线行情数据
    stock_data = ak.stock_zh_a_daily(symbol="sz000001", start_date="2020-01-01", end_date="2021-12-31")

    # 选择用于预测的特征（以日期为基础进行编码）
    stock_data["date"] = pd.to_datetime(stock_data["date"])
    stock_data["day_of_year"] = stock_data["date"].dt.dayofyear
    X = stock_data[["day_of_year"]].values
    y = stock_data["close"].values

    # 训练线性回归模型
    model = LinearRegression()
    model.fit(X, y)

    # 预测未来30天的股价
    future_dates = pd.date_range(start="2023-01-01", periods=30, closed="right")
    future_day_of_year = future_dates.dayofyear.values.reshape(-1, 1)
    future_predictions = model.predict(future_day_of_year)

    # 绘制股价预测图
    plt.figure(figsize=(12, 6))
    plt.plot(stock_data["date"], stock_data["close"], label="历史股价")
    plt.plot(future_dates, future_predictions, label="预测股价", linestyle="--")
    plt.xlabel("Date")
    plt.ylabel("Close Price")
    plt.title("Stock Price Prediction")
    plt.legend()
    plt.show()
